package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableUserAmountRetrialAudit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TagUserAmountRetrialAudit {
    public long uid;
    public int amount_retrial_submit_time;
    public int amount_retrial_success_time;
    public int amount_retrial_fail_time;
    public int update_time;

    public TagUserAmountRetrialAudit(
            long uid,
            int amount_retrial_submit_time,
            int amount_retrial_success_time,
            int amount_retrial_fail_time) {
        this.uid = uid;
        this.amount_retrial_submit_time = amount_retrial_submit_time;
        this.amount_retrial_success_time = amount_retrial_success_time;
        this.amount_retrial_fail_time = amount_retrial_fail_time;
    }

    public static TagUserAmountRetrialAudit init(long uid) {
        return new TagUserAmountRetrialAudit(uid, 0, 0, 0);
    }

    public static Logger LOG = LoggerFactory.getLogger(TagUserAmountRetrialAudit.class);

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableUserAmountRetrialAudit.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUserAmountRetrialAudit>> inputStream =
                tableEnv.toRetractStream(tableRes, TableUserAmountRetrialAudit.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableUserAmountRetrialAudit>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableUserAmountRetrialAudit> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagUserAmountRetrialAudit-filter")
                        .keyBy(
                                new KeySelector<
                                        Tuple2<Boolean, TableUserAmountRetrialAudit>, Long>() {
                                    @Override
                                    public Long getKey(
                                            Tuple2<Boolean, TableUserAmountRetrialAudit> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableUserAmountRetrialAudit>, String>() {
                                    ValueState<TagUserAmountRetrialAudit>
                                            tagUserAmountRetrialAuditVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        tagUserAmountRetrialAuditVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagUserAmountRetrialAudit>(
                                                                        "TagUserAmountRetrialAuditVState",
                                                                        TagUserAmountRetrialAudit
                                                                                .class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableUserAmountRetrialAudit> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        int audit_status = value.f1.getAudit_status();
                                        int create_time =
                                                (int) (value.f1.getCreate_time().getTime() / 1000);
                                        int audit_time =
                                                (int) (value.f1.getAudit_time().getTime() / 1000);
                                        int update_time =
                                                (int) (value.f1.getUpdate_time().getTime() / 1000);

                                        TagUserAmountRetrialAudit tmpState =
                                                tagUserAmountRetrialAuditVState.value();
                                        TagUserAmountRetrialAudit curState =
                                                tmpState == null
                                                        ? TagUserAmountRetrialAudit.init(uid)
                                                        : tmpState;
                                        JSONObject jsonObject = new JSONObject();
                                        jsonObject.put("uid", uid);

                                        if (curState.getAmount_retrial_submit_time()
                                                < create_time) {
                                            curState.amount_retrial_submit_time = create_time;
                                            jsonObject.put(
                                                    "amount_retrial_submit_time",
                                                    curState.getAmount_retrial_submit_time());
                                            out.collect(jsonObject.toString());
                                            tagUserAmountRetrialAuditVState.update(curState);
                                        }

                                        switch (audit_status) {
                                            case 2: // success
                                                if (curState.getAmount_retrial_success_time()
                                                        < audit_time) {
                                                    curState.amount_retrial_success_time =
                                                            audit_time;
                                                    jsonObject.put(
                                                            "amount_retrial_success_time",
                                                            curState
                                                                    .getAmount_retrial_success_time());

                                                    out.collect(jsonObject.toString());
                                                    tagUserAmountRetrialAuditVState.update(
                                                            curState);
                                                }
                                                break;
                                            case 3:
                                                if (curState.getAmount_retrial_fail_time()
                                                        < audit_time) {
                                                    curState.amount_retrial_fail_time = audit_time;
                                                    jsonObject.put(
                                                            "amount_retrial_fail_time",
                                                            curState.amount_retrial_fail_time);

                                                    out.collect(jsonObject.toString());
                                                    tagUserAmountRetrialAuditVState.update(
                                                            curState);
                                                }
                                                break;
                                            default:
                                                LOG.error(
                                                        "uid: "
                                                                + uid
                                                                + " audit_status: "
                                                                + audit_status
                                                                + " not support now!!");
                                                break;
                                        }
                                    }
                                });
        return out;
    }

    public int getUpdate_time() {
        return update_time;
    }

    public int getAmount_retrial_submit_time() {
        return amount_retrial_submit_time;
    }

    public int getAmount_retrial_success_time() {
        return amount_retrial_success_time;
    }

    public int getAmount_retrial_fail_time() {
        return amount_retrial_fail_time;
    }
}
